package com.kgc.cgprovider.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kgc.basic.util.PageInfo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.cgapi.pojo.PurchaseInvoice;
import com.kgc.cgapi.pojo.PurchaseInvoiceDetail;
import com.kgc.cgprovider.dao.PurchaseInvoiceMapper;
import com.kgc.cgprovider.service.PurchaseInvoiceService;
import com.kgc.store.pojo.KcInstore;
import com.kgc.store.pojo.KcInstoreDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseInvoiceServiceImpl implements PurchaseInvoiceService {
    private Logger logger = LoggerFactory.getLogger(PurchaseInvoiceServiceImpl.class);

    @Autowired
    private PurchaseInvoiceMapper purchaseInvoiceMapper;

    @Override
    public ResponseMsg selectPurchaseInvoiceByPage(Map<String, Object> map) {
        logger.info("PurchaseInvoiceServiceImpl selectPurchaseInvoiceByPage map:{}", map);
        ResponseMsg msg = new ResponseMsg();
        PageInfo<PurchaseInvoice> pageInfo = new PageInfo<>();
        pageInfo.setPageNo(map.get("pageNo") == null ? 1 : Integer.parseInt(map.get("pageNo").toString()));
        pageInfo.setPageSize(map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString()));
        Page<Object> page = PageHelper.startPage(pageInfo.getPageNo(), pageInfo.getPageSize(), "order_creation_time desc");
        List<PurchaseInvoice> purchaseInvoiceList = purchaseInvoiceMapper.selectPurchaseInvoiceByPage(map);
        pageInfo.setList(purchaseInvoiceList);
        pageInfo.setTotal((int) page.getTotal());
        msg.setData(pageInfo);
        logger.debug("PurchaseInvoiceServiceImpl selectPurchaseInvoiceByPage result:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg insertPurchaseInvoice(Map<String, Object> map) {
        logger.info("PurchaseInvoiceServiceImpl insertPurchaseInvoice map:{}", map);
        ResponseMsg msg = new ResponseMsg();
        ObjectMapper mapper = new ObjectMapper();

        try {
            // 转换 PurchaseInvoice 对象
            PurchaseInvoice purchaseInvoice = mapper.convertValue(map.get("purchaseInvoice"), PurchaseInvoice.class);
            List<?> rawDetails = (List<?>) map.get("details");
            List<PurchaseInvoiceDetail> details = mapper.convertValue(rawDetails, new TypeReference<List<PurchaseInvoiceDetail>>() {
            });

            // 设置时间字段
            purchaseInvoice.setModifyTime(new Date());
            purchaseInvoice.setOrderCreationTime(new Date());

            // 插入主表
            int result = purchaseInvoiceMapper.insertPurchaseInvoice(purchaseInvoice);
            if (result <= 0) {
                msg.setCode("301");
                msg.setMsg("新增采购发票失败");
                return msg;
            }

            // 插入明细表
            for (PurchaseInvoiceDetail detail : details) {
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
                detail.setIsDelete(0);
                purchaseInvoiceMapper.insertPurchaseInvoiceDetail(detail);
            }

            msg.setCode("200");
            msg.setMsg("新增采购发票成功");
        } catch (Exception e) {
            logger.error("PurchaseInvoiceServiceImpl insertPurchaseInvoice error", e);
            msg.setCode("500");
            msg.setMsg("新增采购发票失败: " + e.getMessage());
            throw new RuntimeException("新增采购发票失败", e); // 抛出异常以触发事务回滚
        }

        logger.debug("PurchaseInvoiceServiceImpl insertPurchaseInvoice result:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg selectPurchaseInstoreByPid(int supplierId) {
        logger.info("PurchaseInvoiceServiceImpl selectPurchaseInstoreByPid supplierId:{}", supplierId);
        ResponseMsg msg = new ResponseMsg();
        List<KcInstore> kcInstores = purchaseInvoiceMapper.selectPurchaseInstoreByPid(supplierId);
        if (kcInstores == null || kcInstores.isEmpty()) {
            msg.setCode("301");
            msg.setMsg("未查询到采购入库信息");
            return msg;
        }
        msg.setCode("200");
        msg.setData(kcInstores);
        return msg;
    }

    @Override
    public ResponseMsg selectPurchaseInstoreDetailByInstoreCode(String instoreCode) {
        logger.info("PurchaseInvoiceServiceImpl selectPurchaseInstoreDetailByInstoreCode instoreCode:{}", instoreCode);
        ResponseMsg msg = new ResponseMsg();
        List<KcInstoreDetail> kcInstoreDetailList = purchaseInvoiceMapper.selectPurchaseInstoreDetailByInstoreCode(instoreCode);
        if (kcInstoreDetailList == null || kcInstoreDetailList.isEmpty()) {
            msg.setCode("301");
            msg.setMsg("未查询到采购入库明细");
            return msg;
        }
        msg.setCode("200");
        msg.setData(kcInstoreDetailList);
        return msg;
    }

    @Override
    public ResponseMsg selectPurchaseInvoiceByCode(String code) {
        logger.info("PurchaseInvoiceServiceImpl selectPurchaseInvoiceByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        PurchaseInvoice purchaseInvoice = purchaseInvoiceMapper.selectPurchaseInvoiceByCode(code);
        if (purchaseInvoice != null) {
            msg.setCode("301");
            msg.setData(purchaseInvoice);
            msg.setMsg("采购发票单据编号重复！");
            return msg;
        }
        msg.setCode("200");
        return msg;

    }

    @Override
    public ResponseMsg selectPurchaseInvoiceDetailByCode(String invoiceCode) {
        logger.info("PurchaseInvoiceServiceImpl selectPurchaseInvoiceDetailByCode invoiceCode:{}", invoiceCode);
        ResponseMsg msg = new ResponseMsg();
        List<PurchaseInvoiceDetail> purchaseInvoiceDetailList = purchaseInvoiceMapper.selectPurchaseInvoiceDetailByCode(invoiceCode);
        if (purchaseInvoiceDetailList == null || purchaseInvoiceDetailList.isEmpty()) {
            msg.setCode("301");
            msg.setMsg("未查询到采购订单的明细");
            return msg;
        }
        msg.setCode("200");
        msg.setData(purchaseInvoiceDetailList);
        return msg;
    }

    @Override
    public ResponseMsg deletePurchaseInvoice(int id) {
        logger.info("PurchaseInvoiceServiceImpl deletePurchaseInvoice id:{}", id);
        ResponseMsg msg = new ResponseMsg();
        int i = purchaseInvoiceMapper.deletePurchaseInvoice(id);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除采购发票成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除采购发票失败");
        return msg;
    }

    @Override
    public ResponseMsg deletePurchaseInvoiceByCode(String code) {
        logger.info("PurchaseInvoiceServiceImpl deletePurchaseInvoiceByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        int i = purchaseInvoiceMapper.deletePurchaseInvoiceByCode(code);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除主表成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除主表失败");
        return msg;
    }

    @Override
    public ResponseMsg deletePurchaseInvoiceDetailByCode(String code) {
        logger.info("PurchaseInvoiceServiceImpl deletePurchaseInvoiceDetailByCode code:{}", code);
        ResponseMsg msg = new ResponseMsg();
        int i = purchaseInvoiceMapper.deletePurchaseInvoiceDetailByCode(code);
        if (i > 0) {
            msg.setCode("200");
            msg.setMsg("删除明细表成功");
            return msg;
        }
        msg.setCode("301");
        msg.setMsg("删除明细表失败");
        return msg;
    }
}
